<template>
  <div class="course-wrap container" v-wechat-title="$route.meta.title + '-' + title">
    <div class="course-title">确认订单</div>
    <el-row type="flex" align="middle" justify="space-between" class="course-tab">
      <span>课程详情</span>
      <span>售价</span>
    </el-row>
    <div class="course-buy">
      <!-- 优惠卷 -->
      <div class="pay-coupons">
        <el-row
          type="flex"
          align="middle"
          class="pay-coupons-head"
          v-if="!$util.isEmpty(couponList) && $util.isEmpty(orderInfo.positive_promotion)"
        >
          <div class="name">使用优惠券</div>
          <el-popover placement="bottom-start" trigger="hover">
            <div class="coursePay-coupon-popover">
              <el-scrollbar class="scrollbar">
                <div class="coursePay-coupon__list">
                  <!-- 优惠卷 -->
                  <el-row
                    type="flex"
                    align="middle"
                    class="item"
                    v-for="(item, index) in couponList"
                    :key="index"
                  >
                    <span class="cond manjian" v-if="item.coupon_type == 1">{{
                      item.price | formatMoney
                    }}</span>
                    <span class="cond dazhe" v-else-if="item.coupon_type == 2"
                      >{{ item.discount | floatCount }}折</span
                    >
                    <span class="cond lesson" v-else-if="item.coupon_type == 3">课程卡</span>
                    <div class="info">
                      <div class="name" v-if="item.coupon_type == 1">
                        满{{ item.maxprice | floatCount }}减{{ item.price | floatCount }} 仅限<span
                          class="mhm"
                          >{{ item.school_name }}</span
                        >使用
                      </div>
                      <div class="name" v-else-if="item.coupon_type == 2">
                        仅限
                        <span class="mhm">{{ item.school_name }}</span>
                        使用
                      </div>
                      <div class="name" v-else-if="item.coupon_type == 3">
                        仅限
                        <span class="mhm">{{ item.course_title }}</span>
                        使用
                      </div>

                      <div v-if="item.use_etime" class="time">
                        {{ item.use_stime | parseTime('{y}.{m}.{d}') }}-{{
                          item.use_etime | parseTime('{y}.{m}.{d}')
                        }}
                      </div>
                      <div v-else class="time">永久有效</div>
                    </div>
                    <el-button
                      plain
                      size="mini"
                      class="btn"
                      :disabled="item.id == coupon_id"
                      @click="handieCouponChat(item)"
                      >{{ item.id == coupon_id ? '已使用' : '使用' }}</el-button
                    >
                  </el-row>
                </div>
              </el-scrollbar>
            </div>
            <div class="coursePay-coupon-footer">
              <el-button plain @click="noCoupon" size="mini">不使用卡券</el-button>
            </div>
            <el-button type="text" slot="reference">
              {{ couponText }}<i class="el-icon-arrow-down el-icon--right"></i
            ></el-button>
          </el-popover>
        </el-row>
        <div class="pay-coupons-list" v-if="!$util.isEmpty(orderInfo)">
          <el-row type="flex" justify="space-between" class="item">
            <EduCourseImage
              :image="orderInfo.cover_url"
              :courseType="orderInfo.course_type"
              :promotionType="orderInfo.promotion_type"
              width="170px"
              height="94px"
              :borderRadius="4"
            ></EduCourseImage>
            <el-row type="flex" justify="space-between" class="col">
              <div class="name">{{ orderInfo.title }}</div>
              <el-row type="flex">
                <div class="count">课时数：{{ orderInfo.section_count }}节</div>
                <div class="count" v-if="orderInfo.term_time === 0">
                  永久有效
                </div>
                <div class="count" v-else-if="('' + orderInfo.term_time).length < 5">
                  购买之日起<span>{{ orderInfo.term_time }}</span
                  >天内有效
                </div>
                <div class="count" v-else>
                  {{ orderInfo.term_time | parseTime('{y}年{m}月{d}日前有效') }}
                </div>
              </el-row>
            </el-row>
            <div class="pirce">
              <span v-if="isVip == 1">VIP价</span>
              {{ orderInfo.user_price | formatMoney }}
            </div>
          </el-row>
        </div>
      </div>
      <!-- 积分抵扣 -->
      <Integral
        :credit_arr="credit_arr"
        :value="credit_price"
        :credit_redeem="credit_redeem"
        @change="changePoints"
      ></Integral>
      <el-divider></el-divider>
      <!-- 付款信息 -->
      <el-row class="pay-buy" type="flex" align="middle" justify="end">
        <el-row type="flex" justify="space-between" class="money" v-if="!$util.isEmpty(orderInfo)">
          <el-row type="flex" align="middle" justify="space-between">
            <div class="text">合计</div>
            <div class="price">{{ total_price | formatMoney }}</div>
          </el-row>
          <el-row type="flex" align="middle" justify="space-between">
            <div class="text">优惠</div>
            <div class="sale">-{{ total_reduced_price | formatMoney }}</div>
          </el-row>
        </el-row>
        <el-button type="primary" @click="handleOrder" :disabled="disabled">提交订单</el-button>
      </el-row>
    </div>
  </div>
</template>

<script>
import projectSetting from '@/settings/projectSetting.js'
import { floatCount } from '@/utils/filters.js'
import { mapMutations } from 'vuex'
import EduCourseImage from '@/components/EduCourseImage'
import Integral from './components/integral'
export default {
  components: {
    EduCourseImage,
    Integral
  },
  data() {
    return {
      orderInfo: {},
      couponList: [],
      course_id: this.$route.query.cid,
      coupon_id: 0, // 使用的卡卷id
      ticket_id: 0, // 活动卷id
      coupon_state: 0, // 卡卷状态
      reduced_price: 0, // 优惠价格
      price: 0,
      total_price: 0,
      couponText: '使用优惠卷',
      disabled: false,
      promotion_id: 0,
      credit_arr: [],
      creditValue: 0,
      credit_redeem: 0, // 是否开启积分抵扣
      creditObj: {},
      credit_price: 0,
      credit_reduced_price: 0,
      total_reduced_price: 0
    }
  },
  created() {
    // 活动id，无活动默认为0
    this.promotion_id = this.$util.isEmpty(this.$route.query.pid) ? 0 : this.$route.query.pid
    this.getOrderInfo()
  },
  computed: {
    // 用户会员状态
    isVip() {
      return this.$store.getters['user/accountInfo'].is_vip
    },
    title() {
      return this.orderInfo.title || ''
    }
  },
  methods: {
    ...mapMutations({
      changeOrderData: 'order/SET_ORDER_DATA'
    }),
    // 获取订单信息
    getOrderInfo() {
      let _this = this
      _this.$api.getCourseOrder(
        {
          from: projectSetting.globDeviceType,
          course_id: _this.course_id,
          promotion_id: _this.promotion_id
        },
        res => {
          const { data } = res
          _this.orderInfo = res.data
          if (
            !_this.$util.isEmpty(data.positive_promotion) &&
            data.positive_promotion.running_status == 1
          ) {
            _this.price = data.positive_promotion.price
            _this.total_price = data.positive_promotion.price
          } else {
            _this.price = data.user_price
            _this.total_price = data.user_price
          }
          _this.credit_redeem = data.credit_redeem
          _this.getOrderCourseCredit()
          _this.getCouponCourseList()
        },
        error => {
          this.$message.error(error.msg)
        }
      )
    },
    // 提交订单
    handleOrder() {
      let _this = this
      _this.disabled = true
      let query = {
        from: projectSetting.globDeviceType,
        course_id: _this.course_id.toString(),
        promotion_id: _this.promotion_id
      }
      if (this.ticket_id) {
        query = {
          ...query,
          ticket_id: _this.coupon_id.toString()
        }
      } else {
        query = {
          ...query,
          coupon_id: _this.coupon_id.toString()
        }
      }
      if (!this.$util.isEmpty(_this.creditObj)) {
        query = {
          ...query,
          credit: JSON.stringify(_this.creditObj)
        }
      }
      _this.$api.createCourseOrder(
        query,
        res => {
          _this.disabled = false
          // 是否需要支付
          if (res.data.need_pay) {
            _this.changeOrderData({
              order_no: res.data.order_no,
              payment: res.data.payment,
              return_url: this.$route.query.redirect
            })
            _this.$router.push({
              path: '/buy/confirm'
            })
          } else {
            _this.$message.success(res.msg)
            _this.$router.replace({
              path: _this.$route.query.redirect
            })
          }
        },
        error => {
          _this.disabled = false
          _this.$message.error(error.msg)
        }
      )
    },
    // 获取用户领取的课程卡卷
    getCouponCourseList() {
      this.$api.getCouponCourseUser(
        {
          course_id: this.course_id
        },
        res => {
          this.couponList = res.data
        }
      )
    },
    // 使用卡卷
    handieCouponChat(item) {
      this.coupon_id = item.id
      if (this.$util.isDef(item.ticket_id)) {
        this.ticket_id = item.ticket_id
      } else {
        this.ticket_id = 0
      }
      if (item.coupon_type == 1) {
        this.reduced_price = floatCount(item.price)
        this.couponText = '满' + floatCount(item.maxprice) + '减' + floatCount(item.price)
      } else if (item.coupon_type == 2) {
        this.reduced_price = floatCount(
          this.orderInfo.user_price - this.orderInfo.user_price * (item.discount / 10)
        ).toFixed(2) // 优惠价格
        this.couponText = floatCount(item.discount) + '折'
      } else if (item.coupon_type == 3) {
        this.reduced_price = this.price
        this.couponText = '课程卡'
      }
      this.getOrderCourseCredit()
    },
    // 不适用优惠卷
    noCoupon() {
      if (!this.coupon_id) return
      this.coupon_id = 0
      this.ticket_id = 0
      this.reduced_price = 0
      this.couponText = '使用优惠卷'
      this.getOrderCourseCredit()
    },
    // 积分抵扣
    changePoints(obj) {
      let credit = 0
      if (!this.$util.isEmpty(obj)) {
        credit = obj.num
      }
      this.creditObj = obj
      this.credit_price = credit
      this.credit_reduced_price = credit
      this.handieTotal()
    },
    // 总价
    handieTotal() {
      let price = parseFloat(this.price * 100).toFixed(2)
      let reduced_price = parseFloat(this.reduced_price * 100).toFixed(2)
      let credit_reduced_price = parseFloat(this.credit_reduced_price * 100).toFixed(2)
      let t = price - reduced_price - credit_reduced_price
      this.total_price = t / 100
      this.total_reduced_price = parseFloat(this.reduced_price)
    },
    // 获取积分
    getOrderCourseCredit() {
      const _this = this
      let query = {
        course_id: _this.course_id,
        promotion_id: _this.promotion_id
      }
      if (this.ticket_id) {
        query = {
          ...query,
          ticket_id: this.coupon_id
        }
      } else {
        query = {
          ...query,
          coupon_id: this.coupon_id
        }
      }
      _this.$api.getOrderCourseCredit(query, res => {
        const { data } = res
        _this.credit_arr = data
        _this.changePoints(data[0])
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.scrollbar {
  height: 100%;
  ::v-deep .el-scrollbar__wrap {
    overflow-x: auto;
  }
}
.coursePay-coupon-popover {
  height: 330px;
  .coursePay-coupon__list {
    padding-right: 10px;
  }
  .item {
    .cond.manjian {
      background-image: url('../../assets/images/public/manjian.png');
    }
    .cond.dazhe {
      background-image: url('../../assets/images/public/dazhe.png');
    }
    .cond.lesson {
      background-image: url('../../assets/images/public/lesson.png');
    }
    .cond {
      color: #fff;
      width: 58px;
      height: 32px;
      font-size: 14px;
      font-weight: bold;
      line-height: 32px;
      text-align: center;
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }
    .info {
      flex: 1;
      margin-left: 14px;
      margin-right: 14px;
      font-size: 12px;
      .name {
        color: $text-color-import;
        display: flex;
        .mhm {
          @include edu-color-auxiliary;
          max-width: 120px;
          @include ellipsis();
        }
      }
      .time {
        margin-top: 2px;
        color: $text-color-auxiliary;
      }
    }
    .btn {
      border-radius: 0;
      @include edu-color-primary(border-color);
      @include edu-color-auxiliary;
      width: 60px;
      height: 28px;
      padding: 0;
      &.is-disabled {
        border-color: #ebeef5;
        color: #c0c4cc;
      }
    }
  }
}
.coursePay-coupon-footer {
  padding-top: 12px;
}
.course-wrap {
  margin-top: 10px;
  margin-bottom: 20px;
  padding-bottom: 40px;
  background-color: #ffffff;
  .course-title {
    padding-left: 30px;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    color: $text-color-import;
    line-height: 44px;
  }
  .course-tab {
    padding: 0 56px 0 210px;
    margin: 0 6px;
    height: 44px;
    font-size: 14px;
    font-weight: 500;
    color: $text-color-secondary;
    background: rgba(246, 249, 255, 1);
  }
}
.course-buy {
  margin-top: 20px;
  .pay-coupons {
    padding: 0 30px;
    .pay-coupons-head {
      .name {
        font-size: 14px;
        font-weight: 400;
        color: $text-color-import;
        margin-right: 20px;
      }
      .el-button--text {
        padding: 3px 5px;
        color: $text-color-price;
        border: 1px dashed $text-color-price;
        border-radius: 0;
      }
    }
    .pay-coupons-list {
      margin-top: 10px;
      padding: 2px 20px 22px;
      border: 1px solid rgba(235, 238, 245, 1);
      .item {
        margin-top: 20px;
        .col {
          flex: 1;
          flex-direction: column;
          margin-left: 10px;
          padding-bottom: 15px;
        }
        .name {
          font-size: 13px;
          font-weight: 500;
          color: $text-color-import;
          line-height: 18px;
        }
        .count {
          font-size: 12px;
          color: $text-color-secondary;
          & + .count {
            margin-left: 10px;
          }
        }
        .pirce {
          font-size: 14px;
          font-weight: 500;
          color: $text-color-price;
        }
      }
    }
  }
  .pay-buy {
    padding: 0 30px;
    .money {
      flex-direction: column;
      width: 130px;
      margin-right: 40px;
      .text {
        font-size: 13px;
        font-weight: 400;
        color: $text-color-secondary;
      }
      .price {
        font-size: 18px;
        font-weight: 500;
        color: $text-color-price;
      }
      .sale {
        font-size: 14px;
        font-weight: 400;
        color: $text-color-secondary;
      }
    }
  }
}
</style>
